package com.example.demo.commom;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:龙宝
 * Date:2023-10-08
 * Time:16:22
 * 文件的读写操作
 */
public class FileOperations {
    //1、读文件操作
    /*
    filename变量中不仅包含了文件名，文件路径也在其中
     */
    public static String readFile(String fileName) {
        StringBuilder result = new StringBuilder();
        try(FileReader fileReader = new FileReader(fileName)) {
            while (true) {
                int ch = fileReader.read();
                if(ch == -1) {
                    break;
                }
                result.append((char)ch);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    //2、写文件操作
    public static void writeFile(String fileName,String content) {
        try(FileWriter fileWriter = new FileWriter(fileName)) {
            fileWriter.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
